package {
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
	
	/**
	 * ...
	 * @author Jordan Laine
	 */
	public class Preloader extends MovieClip {
		
		private var bg:Sprite = new Sprite;
		private var bkg:Sprite = new Sprite;
		private var hex1:uint = 0xf0f0f0;
		public function Preloader() {
			
			if (stage) {
				//stage.scaleMode = StageScaleMode.NO_SCALE;
				//stage.align = StageAlign.TOP_LEFT;
			}
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
			addChild(bkg);
			this.addChild(bg);
		}
		
		private function ioError(e:IOErrorEvent):void {
			trace(e.text);
		}
		
		private function progress(e:ProgressEvent):void {
			var percent:Number = (e.bytesLoaded / e.bytesTotal);
			
			bkg.graphics.lineStyle(2, 0xffffff, 0.5);
			bkg.graphics.beginFill(0x353535, 1);
			bkg.graphics.drawRect(0, 0, stage.width, stage.height);
			bkg.graphics.endFill();
			
			bg.graphics.beginFill(hex1++, 1);
			bg.graphics.lineStyle(2, 0xffffff, .5);
			bg.graphics.drawRect(bkg.width * .5 - bg.width * .5, bkg.height * 0.5 - 30, 640 * percent, 60 );
			bg.graphics.endFill();
		}
		
		private function checkFrame(e:Event):void {
			if (currentFrame == totalFrames) {
				stop();
				loadingFinished();
			}
		}
		
		private function loadingFinished():void {
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			this.removeChild(bg);
			this.removeChild(bkg);
			bg = null;
			bkg = null;
			startup();
		}
		
		private function startup():void {
			var mainClass:Class = getDefinitionByName("SOS") as Class;
			trace("Load Complete!");
			addChild(new mainClass() as DisplayObject);
		}	
	}
}